﻿import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { history } from '@umijs/max';
import storage, { GLOBAL_NAMESPACE } from './utils/storage';
import dayjs from 'dayjs';
import message from './utils/message';
import getRandomString from './utils/getRandomString';
import { SecretKey } from './utils';
import { md5 } from 'js-md5';

export const getToken = (): string => {
  const current = storage.get<any>(GLOBAL_NAMESPACE, 'currentUser');
  if (!current) {
    return '';
  }
  const currentUser = typeof current === 'string' ? JSON.parse(current) : current;
  return currentUser.token;
};

export const getCurrentUser = (): API.CurrentUser | null => {
  const current = storage.get<any>(GLOBAL_NAMESPACE, 'currentUser');
  if (!current) {
    return null;
  }
  const currentUser = typeof current === 'string' ? JSON.parse(current) : current;
  return currentUser;
};

export const handel401 = (msg?: string) => {
  if (msg) {
    message.error(msg);
  }
  storage.remove(GLOBAL_NAMESPACE, 'currentUser');
  if (window.location.pathname === '/user/login') {
    return;
  }
  const redirect = window.location.pathname + window.location.search;
  history.replace(`/user/login?redirect=${redirect}`);
};

// 错误处理方案： 错误类型
// enum ErrorShowType {
//   SILENT = 0,
//   WARN_MESSAGE = 1,
//   ERROR_MESSAGE = 2,
//   NOTIFICATION = 3,
//   REDIRECT = 9,
// }

export type APIResult<T = any> = {
  body: T;
  rsCode: string;
  msg: string;
  count?: number;
};

// 与后端约定的响应数据格式
interface ResponseStructure {
  config: any;
  data: APIResult;
  headers: any;
  status: number;
  statusText: string;
}
const downloadBlob = (response: any) => {
  const blob = response.data; // 获取响应中的 Blob 数据
  const contentDisposition = response.headers['content-disposition'];
  let fileName = ''; // 默认文件名
  if (contentDisposition) {
    // 提取文件名并解码成中文
    const fileNameRegex = /filename=([^;]+)/;
    const fileNameMatch = contentDisposition.match(fileNameRegex);
    fileName = fileNameMatch ? fileNameMatch[1] : '';
    if (fileName) {
      fileName = decodeURIComponent(fileName);
    }
  }
  // 创建 Blob 对象后，你可以根据需要执行文件下载逻辑
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `File${dayjs().format('YYYYMMDD')}`; // 设置下载文件的名称
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  // 清除创建的链接
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
};

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const errorConfig: RequestConfig = {
  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      // 签名
      const timestamp = new Date().getTime().toString();
      const nocestr = getRandomString(64);
      const sign = md5(`shmars${nocestr}${timestamp}${SecretKey}shmars`);
      const signMap: Record<string, string> = {
        timestamp,
        nocestr,
        sign,
      };

      // 拦截请求配置，进行个性化处理。
      let url = `${config?.url}`;
      const token = getToken();
      if (!token && !!config.isAuth) {
        handel401();
      } else {
        config.headers = {
          'Content-Type': 'application/json',
          ...config.headers,
          Authorization: token,
          ...signMap,
        };
        if (config.blob) {
          config.responseType = 'blob';
        }
      }
      return { ...config, url };
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response) => {
      // 拦截响应数据，进行个性化处理
      const { data } = response as unknown as ResponseStructure;
      if (data instanceof Blob) {
        downloadBlob(response as any);
      } else {
        if (data.rsCode === '401' || data.rsCode === '3000') {
          handel401(data.msg);
        } else if (data.rsCode !== '00000000') {
          message.error(data.msg);
        }
      }
      return response;
    },
  ],
};
